import queue_globals as vars
from util import getGETparam
import logging

class inactive_handler(object):
    """
    This is the handler which handles a pymq node in the inactive state.
    It is responsible for intercepting activation requests from the
    cluster's master node and initializing the real request handler
    so that this node is then ready to serve requests.
    """
    def __init__(self, owner, on_activate_handler):
        self.owner = owner
        self.on_activate_handler = on_activate_handler

    def initialize(self):
        pass

    def match (self, request):
        return 1

    def handle_request (self, request):
        resource = request.split_uri()[0]
        logging.debug("inactive_handler::handle_request(%s)" % resource)
        request.channel.current_request = None
        if resource == "/_ah/command/node/activate/":
            # Fetch the connection string
            connectionString = getGETparam(request, "connectionString")

            print "Replacing some node with self. Converting self to active."
            print "Setting connection string to %s" % connectionString
            # Initialize the underlying handler
            vars.DataStore.setConnectionString(connectionString)
            self.on_activate_handler.initialize()
            self.owner.remove_handler(self)
            self.owner.add_handler(self.on_activate_handler)
            request.done()
        else:
            request.error(404)
